const http = require('http');

// 创建server服务
const server = http.createServer((req, res) => {
    // 设置响应头
    res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8'
    });
    // 获取请求方法
    if (req.method === 'GET') {
        // 请求地址
        if (req.url === '/hello') {
            // 结束响应
            res.end(JSON.stringify(
                {
                    code: 200,
                    msg: 'hello world'
                }
            ));
        }
    } else if (req.method === "POST") {
        // 请求地址
        if (req.url === '/login') {
            // 获取post参数
            let postData = '';
            req.on('data', (chunk) => {
                postData += chunk.toString();
            })

            // 设置响应内容
            req.on('end', () => {
                res.end(JSON.stringify({
                    code: 200,
                    msg: '登录成功',
                    data: JSON.parse(postData)
                }));
            });
        }
    }
})

// 监听端口
server.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})